﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Web;
using System.Net.Mail;
using System.Net;
using System.IO;

namespace MailService
{
	public class MailHelper
	{
		private readonly static ServiceGroupDevelopmentDBEntities EF = new ServiceGroupDevelopmentDBEntities();
		private static List<EmailLogs> mailList = new List<EmailLogs>();

		#region 从集合中取出数据，发送邮件
		/// <summary>
		/// 从队列中取出数据，发送邮件
		/// </summary>
		public static void StartSend()
		{
            File.AppendAllText("c:/1.txt", "取出数据\r\n");
			mailList = EF.EmailLogs
				.Where(x => x.MailStatus == (int)MailStatusEnum.新增)
				.ToList();
			if (mailList.Count > 0)
			{
				MailHelper.SendMail();
			}
		}
		#endregion

		#region 发送邮件，并记录邮件发送日志
		/// <summary>
		/// 发送邮件
		/// </summary>
		private static void SendMail()
		{
			while (mailList.Count > 0)
			{
				if (HttpRuntime.Cache["MailService"] == null)
				{
					GetSettings();
				}
				foreach (EmailLogs model in mailList)
				{
					model.SenderAddress = HttpRuntime.Cache["MailFrom"].ToString();
					model.SenderName = HttpRuntime.Cache["MailFromName"].ToString();

					//smtp.163.com，smtp.qq.com,发件人所用的SMTP服务器。
					SmtpClient client = new SmtpClient(HttpRuntime.Cache["MailService"].ToString(), 25);
					//指定发件人所使用的邮箱的用户名和密码。
					client.Credentials = new NetworkCredential(HttpRuntime.Cache["UserName"].ToString(), HttpRuntime.Cache["PassWord"].ToString());
					client.Timeout = 10000;

					try
					{
						client.Send(CreateMail(model));
						model.MailStatus = (int)MailStatusEnum.发送成功;
					}
					catch (Exception)
					{
						model.MailStatus = (int)MailStatusEnum.发送失败;
					}
					EF.Entry(model).State = EntityState.Modified;
				}
				EF.SaveChanges();
				mailList.Clear();
			}
		}
		#endregion

		#region 创建邮件
		/// <summary>
		/// 创建邮件
		/// </summary>
		/// <param name="model">Mail信息</param>
		/// <returns></returns>
		private static MailMessage CreateMail(EmailLogs model)
		{
			#region 创建邮件信息
			//创建邮件信息
			MailMessage mailMsg = new MailMessage();
			mailMsg.BodyEncoding = Encoding.UTF8;
			mailMsg.From = new MailAddress(model.SenderAddress, model.SenderName);
			#endregion

			#region 获取收件人地址列表
			//获取收件人地址列表
			string[] receiverAddressList = model.ReceiverAddress.Split(new char[] { ';', '；' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (string item in receiverAddressList)
			{
				mailMsg.To.Add(new MailAddress(item.Trim()));
			}
			#endregion

			#region 获取抄送人地址列表
			//获取抄送人地址列表
			if (!string.IsNullOrEmpty(model.CopyAddress))
			{
				string[] copyAddressList = model.CopyAddress.Split(new char[] { ';', '；' }, StringSplitOptions.RemoveEmptyEntries);
				foreach (string item in copyAddressList)
				{
					mailMsg.CC.Add(item.Trim());
				}
			}
			#endregion

			#region 获取密送人地址列表
			//获取密送人地址列表
			if (!string.IsNullOrEmpty(model.BccAddress))
			{
				string[] bccAddressList = model.BccAddress.Split(new char[] { ';', '；' }, StringSplitOptions.RemoveEmptyEntries);
				foreach (string item in bccAddressList)
				{
					mailMsg.Bcc.Add(item.Trim());
				}
			}
			#endregion

			mailMsg.Priority = (MailPriority)model.Priority;//优先级
			mailMsg.Subject = model.Subject;//发送邮件的标题
			mailMsg.Body = model.Content;//发送邮件的内容
			mailMsg.IsBodyHtml = model.IsContentHTML;//邮件内容是否为HTML格式的

			return mailMsg;
		}
		#endregion

		#region 更新设置的缓存
		/// <summary>
		/// 更新设置的缓存
		/// </summary>
		public static void GetSettings()
		{
			var modelList = EF.Settings.ToList();
			foreach (var item in modelList)
			{
				HttpRuntime.Cache[item.Key] = item.Value;
			}
		}
		#endregion
	}
	/// <summary>
	/// 邮件状态枚举
	/// </summary>
	public enum MailStatusEnum { 新增 = 1, 发送成功 = 2, 发送失败 = 3 }
}
